<template>
  <div class="user-detail-dialog-page">
    <el-dialog
      :model-value="props.dialogVisible"
      title="用户详情"
      width="1200px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <div class="info-block">
        <div>
          <span>基本信息</span>
        </div>
        <el-row class="mt16" :gutter="16">
          <el-col class="info-item" :span="8" v-for="(item, index) in infoData" :key="index">
            <span class="label">{{item.label}}:</span>
            <span v-if="item.prop === 'regTime' || item.prop === 'logInTimeLast'" class="value">
              {{userForm[item.prop] ? moment(userForm[item.prop]).format('YYYY-MM-DD HH:mm:ss') : ''}}
            </span>
            <span v-else class="value">{{userForm[item.prop]}}</span>
          </el-col>
        </el-row>
      </div>
      <div class="device-block">
        <div>
          <span>绑定设备</span>
          <span class="btn">
            <el-button type="primary" @click="batchBindDevice">绑定设备</el-button>
            <el-button @click="batchDeleteDevice">解除绑定</el-button>
          </span>
        </div>
        <el-table ref="multipleTableRef" :data="tableData" :max-height="400" class="nr-table mt16">
          <el-table-column type="selection" width="30"/>
          <el-table-column label="绑定关系" prop="role">
            <template #default="scope">
              <span>{{scope.row.role === 1 ? '使用者' : '管理员'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="设备名称" prop="deviceName"></el-table-column>
          <el-table-column label="设备SN" prop="deviceSn"></el-table-column>
          <el-table-column label="产品" prop="productName"></el-table-column>
          <el-table-column label="分组" prop="projectName"></el-table-column>
          <el-table-column label="安装地址" prop="address"></el-table-column>
          <el-table-column label="安装房间" prop="location"></el-table-column>
          <el-table-column label="最后登录时间" prop="dataLatestTime">
            <template #default="scope">
              <span>{{scope.row.dataLatestTime ? moment(scope.row.dataLatestTime).format('YYYY-MM-DD HH:mm:ss') : ''}}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="online">
            <template #default="scope">
              <el-tag v-if="scope.row.online === 1" type="success">在线</el-tag>
              <el-tag v-if="scope.row.online === -1" type="danger">异常</el-tag>
              <el-tag v-if="scope.row.online === 0" type="info">离线</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-link class="table-btn" type="primary" :underline="false" @click="handleData(scope.row)">数据</el-link>
              <el-link class="table-btn" type="danger" :underline="false" @click="handleDeleteDevice(scope.row)">解绑</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <user-bind-device-dialog
      :dialogVisible="selectDeviceDialogVis"
      :formData="userForm"
      @update:dialogVisible="(value: boolean) => selectDeviceDialogVis = value"
      @submit="getBindDeviceList">
    </user-bind-device-dialog>

    <data-detail-dialog
      :dialogVisible="dataDetailDialogVis"
      :formData="totalData.data"
      @update:dialogVisible="(value: boolean) => dataDetailDialogVis = value">
    </data-detail-dialog>
  </div>
</template>

<script setup lang="ts" name="DeviceDetailDialog">
import { ref, reactive, watch, ComponentInternalInstance, getCurrentInstance, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { useRouter } from 'vue-router'
import UserBindDeviceDialog from './user-bind-device-dialog.vue'
import DataDetailDialog from '@/components/data-detail-dialog/data-detail-dialog.vue'
import { bindDeviceList, unbindBatch } from '@/api/bind'
import moment from 'moment'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const emit = defineEmits(['update:dialogVisible'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: {}
  }
})

const router = useRouter()
const userForm = reactive({
  id: -1,
  pid: '',
  username: '',
  projectName: '',
  phoneNum: '',
  wechatId: '',
  wechatName: '',
  regTime: '',
  logInTimeLast: ''
})
const infoData = ref<any>([
  { label: '用户名称', prop: 'username' },
  { label: '绑定手机', prop: 'phoneNum' },
  { label: '绑定微信', prop: 'wechatId' },
  { label: '用户分组', prop: 'projectName' },
  { label: '注册时间', prop: 'regTime' },
  { label: '最近登录时间', prop: 'logInTimeLast' },
])
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const tableData = ref<any>([])
const selectDeviceDialogVis = ref(false)
const dataDetailDialogVis = ref(false)
const totalData = ref({
  data: {}
})

watch(() => props.dialogVisible, async (newVal) => {
  if (newVal) {
    userForm.id = props.formData.id
    userForm.pid = props.formData.pid
    userForm.username = props.formData.username
    userForm.projectName = props.formData.projectName
    userForm.phoneNum = props.formData.phoneNum
    userForm.wechatId = props.formData.wechatId
    userForm.wechatName = props.formData.wechatName
    userForm.regTime = props.formData.regTime
    userForm.logInTimeLast = props.formData.logInTimeLast
    getBindDeviceList()
  }
})

// 绑定用户
const batchBindDevice = () => {
  selectDeviceDialogVis.value = true
}

// 批量解绑
const batchDeleteDevice = () => {
  let arr = <any>[...multipleTableRef.value?.getSelectionRows()]
  if (arr.length === 0) {
    ElMessage.error(`未选择设备！`)
    return false
  }
  ElMessageBox.confirm(
    `确定要批量解绑设备吗？`,
    '系统提示',
    {
      type: 'warning',
    }
  )
  .then(() => {
    let bindIds = <any>[]
    arr.map((item: any) => {
      bindIds.push(item.bindId)
    })
    let params = {
      bindIdList: bindIds
    }
    unbindBatch(params).then((res: any) => {
      if (res.code === 0) {
        ElMessage.success(`解绑成功！`)
        getBindDeviceList()
      } else {
        ElMessage.error(`${res.msg}`)
      }
    }).catch(err => {
      console.log(err)
    })
  })
  .catch(() => {})
}

// 数据
const handleData = (row: any) => {
  // dataDetailDialogVis.value = true
  // totalData.value.data = Object.assign({}, row)
  router.push({
    path: '/user-data'
  })
}

// 解绑
const handleDeleteDevice = (row: any) => {
  ElMessageBox.confirm(
    `确定要解绑【${row.deviceName}】此设备吗？`,
    '系统提示',
    {
      type: 'warning',
    }
  )
  .then(() => {
    let params = {
      bindIdList: [row.bindId]
    }
    unbindBatch(params).then((res: any) => {
      if (res.code === 0) {
        ElMessage.success(`解绑成功！`)
        getBindDeviceList()
      } else {
        ElMessage.error(`${res.msg}`)
      }
    }).catch(err => {
      console.log(err)
    })
  })
  .catch(() => {})
}

// 关闭弹窗
const handleClose = () => {
  tableData.value = []
  proxy?.$emit('update:dialogVisible', false)
}

// 获取绑定设备
const getBindDeviceList = async () => {
  let params = {
    userId: userForm.id
  }
  await bindDeviceList(params).then((res: any) => {
    if (res.code === 0) {
      tableData.value = [...res.list]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}
</script>

<style lang="stylus" scoped>
@import '../../style/base.styl'

.user-detail-dialog-page
  .info-item
    margin-bottom 16px
    .label
      width 100px
      display inline-block
      text-align right
      color black
      font-weight bold
    .value
      margin-left 4px
  .device-block
    .btn
      margin-left 16px
</style>
